import React, { Component } from 'react'

import { Icon } from 'antd';
import { ClickLink } from '../../styled/list';

import styled from 'styled-components';
import { getFileType } from '@/utils/util';

const CloseIcon = styled(Icon)`
  position: absolute;
  top: 12px;
  right: 15px;
  color: #fefeff;
  font-size: 20px;
  z-index: 2;
  &:hover {
    cursor: pointer;
  }
`

interface IProps {
  hasText?: string,
  missText?: string,
  url: string,
}

export default class Imgviewer extends Component<IProps> {
  state = {
    visible: false,
    url: this.props.url
  }

  static getDerivedStateFromProps(props, state) {
    if (props.url !== state.url) {
      return {
        url: props.url
      }
    }

    return null;
  }

  handleCancel = () => {
    this.setState({
      visible: false
    })
  }

  handleShow = () => {
    this.setState({
      visible: true
    })
  }

  render() {

    const { visible, url } = this.state;
    const type = getFileType(url);

    const href = type === 'office' ? `https://view.officeapps.live.com/op/view.aspx?src=${url}` : url;

    return (
      <>
        { url ?
          <ClickLink onClick={this.handleShow}>{ this.props.hasText || '查看'}</ClickLink> : `${this.props.missText}`
        }
        {
          visible ? (
            <section style={{ position: 'fixed', zIndex: 2, width: '100vw', height: '100vh', top: '0', left: '0' }}>
              <CloseIcon type="close" onClick={this.handleCancel} />
              <iframe
                title='消防管理机构'
                src={href}
                frameBorder="0"
                style={{
                  width: "100%",
                  height: '100%'
                }}
              >
                浏览器不支持预览 <a href={url}>Download File</a>
              </iframe>
            </section>
          ) : null
        }
      </>
    )
  }
}
